package com.finger.crowd.controller;

import com.finger.crowd.util.CrowdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.awt.image.renderable.ParameterBlock;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ProjectConsumerController {

    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    @Autowired
    private OSSProperties properties;

    @RequestMapping("/create/project/information")
    public String createProjectInfomation(
            // 接收来自页面的数据
            ProjectVO projectVO,
            // 接收来自页面的头部信息图片
            MultipartFile headerPicture,
            // 接收页面项目详情的多张图片
            List<MultipartFile> detailPictureList,
            // 把projectVO保存到redis中
            HttpSession session,
            // 请求转发要带一些信息
            Model model
    ) throws IOException {

//        /*
//        写的不舍得删的代码
//        boolean isEmpty = multipartFile.isEmpty();
//
//        if (!isEmpty) {
//
//            ResultEntity<String> resultEntity = CrowdUtils.uploadFileToOss(properties.getEndPoint(),
//                    properties.getAccessKeyId(),
//                    properties.getAccessKeySecret(),
//                    multipartFile.getInputStream(),
//                    properties.getBucketName(),
//                    properties.getBucketDomain(),
//                    "header.jpg");
//
//            if (resultEntity.getResult() == "SUCCESS") {
//                projectVO.setHeaderPicturePath(resultEntity.getData());
//            } else {
//                model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "图片上传失败");
//                return "project-launch";
//            }
//
//        } else {
//            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_UPLOAD_FAILED);
//
//            return "project-launch";
//        }
//        if (multipartFiles.size() == 0 || multipartFiles == null) {
//            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_UPLOAD_FAILED);
//            return "";
//        }
//        */

        // 判断头图和项目详细图片是否为空，如果为空就返回
        if (headerPicture.isEmpty() ||
                detailPictureList.size() == 0 ||
                detailPictureList == null) {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "请上传头图或者项目详情图");
            return "project-launch";
        }

        // 创建List用来存放项目详情图片路径
        List<String> detailPicturePathList = new ArrayList<>();

        // 挨个把项目详情图片上传到oss中，但凡有一个图片上传失败，就返回
        for (MultipartFile detailPic : detailPictureList) {

            if (detailPic.isEmpty()) {

                model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "详情信息图不能为空");

                return "project-launch";
            }

            // 上传到oss对象存贮
            ResultEntity<String> uploadDetailsPicResultEntity = CrowdUtils.uploadFileToOss(
                    properties.getEndPoint(),
                    properties.getAccessKeyId(),
                    properties.getAccessKeySecret(),
                    detailPic.getInputStream(),
                    properties.getBucketName(),
                    properties.getBucketDomain(),
                    "detailPic.jpg");
            // 获取项目详情图片路径
            String detailPicturePath = uploadDetailsPicResultEntity.getData();

            // 存入集合
            detailPicturePathList.add(detailPicturePath);

        }
        // 上传项目头图
        ResultEntity<String> resultEntity = CrowdUtils.uploadFileToOss(
                properties.getEndPoint(),
                properties.getAccessKeyId(),
                properties.getAccessKeySecret(),
                headerPicture.getInputStream(),
                properties.getBucketName(),
                properties.getBucketDomain(),
                "header.jpg");
        // 如果上传失败就返回 project-launch
        if (resultEntity.getResult() == "FAILED") {

            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "头图上传失败");

            return "project-launch";
        }

        // 获取头图得路径
        String headerUploadResultPath = resultEntity.getData();

        // set 头图路径
        projectVO.setHeaderPicturePath(headerUploadResultPath);

        // set项目详情图片路径
        projectVO.setDetailPicturePathList(detailPicturePathList);

        // set projectVO
        session.setAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT, projectVO);

        // 重定向到收集回报页面
        return "redirect:http://www.crowd.com/project/return/info/page";
    }

    @RequestMapping("/create/upload/return/picture.json")
    @ResponseBody
    public ResultEntity uploadReturnPrcture(
            @RequestParam("returnPicture") MultipartFile returnPicture) {
        try {
            // 判断回报图片是否为空
            if (returnPicture.isEmpty()) {
                return ResultEntity.failed("图片上传失败");
            }

            // 将回报图片上传到oss对象存储
            ResultEntity<String> returnPrctureResult = CrowdUtils.uploadFileToOss(
                    properties.getEndPoint(),
                    properties.getAccessKeyId(),
                    properties.getAccessKeySecret(),
                    returnPicture.getInputStream(),
                    properties.getBucketName(),
                    properties.getBucketDomain(),
                    "returnPrctures.jpg");

            return returnPrctureResult;
        } catch (IOException e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    @RequestMapping("/create/save/return.json")
    @ResponseBody
    public ResultEntity saveReturn(ReturnVO returnVO,
                                   HttpSession session) {
        try {

            if (returnVO == null) {
                return ResultEntity.failed("这一条保存失败");
            }

            // 从session域中取出projectVO
            ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT);

            if (projectVO == null) {

                return ResultEntity.failed(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
            }

            List<ReturnVO> returnVOList = projectVO.getReturnVOList();

            if (returnVOList == null || returnVOList.size() == 0) {

                returnVOList = new ArrayList<ReturnVO>();

                //为了让以后的操作能使用到returnVOList，需要重新set回去
                projectVO.setReturnVOList(returnVOList);

            }

            returnVOList.add(returnVO);

            session.setAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT, projectVO);

            return ResultEntity.successWithOutData();
        } catch (Exception exception) {

            exception.printStackTrace();

            return ResultEntity.failed(exception.getMessage());
        }
    }

    @RequestMapping("/save/confirm/page")
    public String saveConfirm(MemberConfirmInfoVO memberConfirmInfoVO,
                              HttpSession session,
                              Model model) {

        if (memberConfirmInfoVO == null) {

            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "易付宝账号或者密码不能为空");

            return "project-confirm";
        }

        // 从session中取出projectVO对象
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT);

        // 从session中取出loginMember对象
        LoginMemberVO loginMember = (LoginMemberVO) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        if (projectVO == null || loginMember == null) {

            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, "projectVO或loginMember已丢失");

            return "project-confirm";
        }

        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        Integer memberId = loginMember.getId();

        ResultEntity resultEntity = mySQLRemoteService.saveProjectVO(projectVO, memberId);

        if (ResultEntity.getFAILED().equals(resultEntity.getResult())) {

            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, resultEntity.getMassage());

            return "project-confirm";
        }

        session.removeAttribute(CrowdConstant.ATTR_NAME_TEMP_PROJECT);

        return "redirect:http://www.crowd.com/project/save/project/success";

    }

    @RequestMapping("/get/detail/projectVO/{projectId}")
    public String getDetailProjectVO(@PathVariable("projectId") Integer projectId,
                                     Model model) {
        ResultEntity<DetailProjectVO> detailProjectVO = mySQLRemoteService.getDetailProjectVO(projectId);

        if (ResultEntity.getSUCCESS().equals(detailProjectVO.getResult())) {

            model.addAttribute(CrowdConstant.ATTR_NAME_DETAIL, detailProjectVO.getData());
        }

        return "project-detail";
    }
}
